using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Reflection;
using Edge.Common.ControlFlow;
using Edge.Common.Services;
using Edge.Common.TextTemplates;
using Edge.Common.Utils;
using Edge.Common.ControlFlow;
using Edge.Common.Services;
using Edge.Common.TextTemplates;
using Edge.Common.Utils;
using log4net;

namespace Edge.Common.Mail
{
    public static class MailUtils
    {
        private static readonly ILog log = LogManager.GetLogger(MethodInfo.GetCurrentMethod().DeclaringType);

        public static void Send(string to, string subject, string body)
        {
            Send(to, null, subject, body);
        }

        public static void Send(string to, string from, string subject, string body)
        {
            MailMessage message = new MailMessage();
            message.To.Add(to);
            if (from !=null)
                message.From = new MailAddress(from);
            else
                message.From = new MailAddress(Locator.GetService<ISendMailService>().DefaultFrom()[0]);
            message.Body = body;
            message.Subject = subject;
            Locator.GetService<ISendMailService>().Send(message);
        }

        public static bool PrepareMailMessage(string subject, string to, List<string> Cc, string from, string body, AttachmentStore attachmentsStore, ref MailMessage mm)
        {
            string strBeginLog = string.Format("Subject: {0}; From {1}; To: {2}; Cc: {3}; Error:", subject, from, to, ListCcToString(Cc));
            try
            {
                subject = subject != null ? subject.Replace('\r', ' ').Replace('\n', ' ') : "";

                mm.IsBodyHtml = true;
                if (!StringUtils.IsBlankOrNull(to))
                {
                    if (to.IndexOf("@") > 0)
                    {
                        if (!StringUtils.IsBlankOrNull(to.Substring(0, to.IndexOf("@"))) &&
                            !StringUtils.IsBlankOrNull(to.Substring(to.IndexOf("@") + 1)))
                            mm.To.Add(to);
                        else
                            log.ErrorFormat(strBeginLog + " The specified string 'EMail To' ('{0}') is not in the form required for an e-mail address.", to);
                    }
                    else
                        log.ErrorFormat(strBeginLog + " The specified string 'EMail To' ('{0}') is not in the form required for an e-mail address.", to);
                }

                if (Cc != null)
                    foreach (string str in Cc)
                    {
                        if (!StringUtils.IsBlankOrNull(str))
                            if (str.IndexOf("@") > 0)
                            {
                                if (!StringUtils.IsBlankOrNull(str.Substring(0, str.IndexOf("@"))) &&
                                    !StringUtils.IsBlankOrNull(str.Substring(str.IndexOf("@") + 1)))
                                    mm.CC.Add(str);
                                else
                                    log.ErrorFormat(strBeginLog + " The specified string 'EMail To' ('{0}') is not in the form required for an e-mail address.", to);
                            }
                            else
                                log.ErrorFormat(strBeginLog + " The specified string for 'Mail Cc' '{0}' is not in the form required for an e-mail address.", str);
                    }
                if (((mm.CC == null) || (mm.CC.Count == 0)) && (StringUtils.IsBlankOrNull(to)))
                {
                    log.Error(strBeginLog + " Not alone EMail address not indicate.");
                    return false;
                }

                if (StringUtils.IsBlankOrNull(from))
                    //mm.From = new MailAddress(Locator.GetService<ISendMailService>().DefaultFrom()[0], Locator.GetService<ISendMailService>().DefaultFrom()[1]); 
                    mm.From = new MailAddress(Locator.GetService<ISendMailService>().DefaultFrom()[0]); 
                //mm.CC.Add(mm.From);
                mm.Body = body;
                mm.Subject = subject;

                foreach (string fileName in attachmentsStore.Files)
                {
                    try
                    {
                        string flName = fileName;
                        if (fileName[0] == '~')
                        {
                            flName = GetTemplatesPath() +
                                     Path.DirectorySeparatorChar.ToString() + fileName.Substring(2);
                        }
                        mm.Attachments.Add(new Attachment(flName));
                    }
                    catch (Exception ex)
                    {
                        log.ErrorFormat(strBeginLog + "; Error: {0}.", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(strBeginLog + "; Error: {0}.", ex);
                return false;
            }
            return true;
        }

        public static string ListCcToString(List<string> Cc)
        {
            string ret = string.Empty;

            if (Cc != null)
                foreach (string str in Cc)
                {
                    if (!StringUtils.IsBlankOrNull(str))
                        ret += str + ", ";
                }
            if (!StringUtils.IsBlankOrNull(ret))
            {
                ret = ret.Trim();
                ret = ret.Substring(0, ret.Length - 1);
            }
            return ret;
        }

        public static string GetTemplatesPath()
        {
            string templatesPath = AppDomain.CurrentDomain.RelativeSearchPath;
            Assert.CheckNotNull(templatesPath);
            if (!templatesPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                templatesPath += Path.DirectorySeparatorChar.ToString();

            templatesPath += "TextTemplates";
            return templatesPath;
        }

    }
}